<?php
/**
 * Description
 * User: duanwenjie
 * Date: 2019/5/31
 * Time: 11:59 AM
 */

namespace app\index\service;
use app\common\model\ToolModel;
use app\common\service\DownService;
use think\Exception;

class ShopsalestockService
{
    static public function getList($param, $is_download = false)
    {
        try{
            $where = "where 1 = 1 ";
            $pageNumber = isset($param['page']) ? $param['page'] : 1;
            $pageData = isset($param['limit']) ? $param['limit'] : 20;
            $base_shop_name = isset($param['base_shop_name']) ? $param['base_shop_name'] : '';  // 店铺名称
            $sku = isset($param['sku']) ? $param['sku'] : '';  // SKU
            $offset = ($pageNumber - 1) * $pageData;
            $limit = " LIMIT $offset,$pageData";

            if (!empty($base_shop_name)) {
                $base_shop_name = trim($base_shop_name);
                $where .= " AND shop_name = '{$base_shop_name}'";
            }
            if (!empty($sku)) {
                $sku = trim($sku);
                $where .= " AND sku = '{$sku}'";
            }

            $sqlCount = "SELECT COUNT(id) num FROM shop_sale_stock {$where}";
            $countArr = ToolModel::queryData($sqlCount);
            if (empty($countArr) || $countArr[0]['num'] == 0) {
                if ($is_download) exitJson(["code" => "500", "msg" => "无有效数据"]);
                return array('total' => 0, 'list' => array());
            }
            $fileds = 'id,sku,sku_name,base_shop_id,shop_name,apply_quantity,po_way_quantity,
                      draw_way_quantity,transfer_warehouse_stock,ship_way_quantity,
                      country_stock_quantity,shop_stock,update_time';

            $sql = "SELECT {$fileds} FROM shop_sale_stock {$where} ORDER BY id DESC {$limit}";
            if ($is_download) return "SELECT {$fileds} FROM shop_sale_stock {$where} ORDER BY id DESC ";

            $list = ToolModel::queryData($sql);
            $data = array();
            $data['total'] = intval($countArr[0]['num']);
            $data['list'] = $list;

            return $data;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 导出数据
     * @param $param
     * @return array
     * @author duanwenjie
     */
    static public function export($param)
    {
        $sql = self::getList($param,true);
        $title = array(
            'shop_name' => '店铺名称',
            'sku' => 'SKU',
            'sku_name' => 'SKU中文名称',
            'apply_quantity' => '申请数量',
            'po_way_quantity' => '采购在途',
            'draw_way_quantity' => '提货在途',
            'transfer_warehouse_stock' => '中转仓库存',
            'ship_way_quantity' => '发运在途',
            'country_stock_quantity' => '国家仓库存',
            'shop_stock' => '店仓库存'
        );

        $res = DownService::getData($sql,$title,'',$param);

        return $res;
    }

}